layui.use(['form', 'layer', 'laydate', 'jquery', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    var tempId = 0;
    var tableIns = table.render({
        elem: '#stateEdit',
        url: '/main/getCaseBoxList?caseNo=' + $("#caseNo").val(),
        page: true,
        toolbar: '#toolbarDemo',
        defaultToolbar: "",
        id: 'boxId',
        height: "full-125",
        limit: 10,
        limits: [10,20,30,40,50,60,70,90,100],
        id: "stateEditTable",
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'doorNum', title: '门号', width: 60, align: "center", fixed: "left"},
            {field: 'switchStatusStr', title: '开关状态', width: 90, align: "center"},
            {field: 'useStatusStr', title: '占用', width: 60, align: 'center'},
            {field: 'saveId', title: '存物ID', minWidth: 200, align: 'center'},
            {field: 'size', title: '柜子尺寸', width: 100, align: 'center', templet: function (f) {
                temp = f.size;
                var a = "", b = "", c = "", d = "";
                if (temp == 0) {
                    a = "selected"
                } else if (temp == 1) {
                    b = "selected"
                } else if (temp == 2) {
                    c = "selected"
                } else if (temp == 3) {
                    d = "selected"
                }
                return '<select lay-ignore="" id="' + f.boxId + '" class="' + (tempId++) + '" class="special-size">  '
                    + '<option value="0" ' + a + '>请选择</option> '
                    + '<option value="1" ' + b + '>大</option> '
                    + '<option value="2" ' + c + '>中</option> '
                    + '<option value="3" ' + d + '>小</option>  </select>'
            }},
            {field: 'goodsPrice', title: '价格', width: 90, align: 'center'},
            {field: 'saveTimeStr', title: '存物时间', minWidth: 170, align: 'center'},
            {field: 'isConn', title: '是否正常', width: 90, align: 'center', templet: function (f) {
                if (f.isConn == "异常") {
                    return "<span class='layui-red'>异常</span>"
                } else {
                    return "<span>正常</span>"
                }
            }},
            {field: 'isLocked', title: '是否锁门', width: 90, align: 'center', templet: function (f) {
                if (f.isLocked == "否") {
                    return "<span class='layui-red'>否</span>"
                } else {
                    return "<span>是</span>"
                }
            }},
            {field: 'isShow', title: '启用', width: 90, align: 'center', templet: "#isShow"},
            {title: '操作', templet: '#stateEditBar', width: 200, align: "center"}
        ]],
        done: function () {
            // 隐藏列
            if ($("#useType").val() != 7) {
                $(".layui-table-box").find("[data-field='goodsPrice']").css("display", "none");
            }
            for (var i = 0; i <= tempId; i++) {
                $("." + i).on("change", function () {
                    boxId = this.id
                    var a = $(this).val()
                    var str = "0123"
                    var judge = (str.indexOf(a) != -1);
                    if (judge) {
                        var caseNo = $("#caseNo").val()
                        // console.log(caseNo)
                        $.get("/main/changeSize?boxId=" + boxId + "&size=" + a + "&caseNo=" + caseNo, function (res) {
                            layer.msg(res.message)
                            if(!res.success){
                        		tableIns.reload();
                        	}
                        })
                    }
                })
            }
        }
    });

  

//	$("#myGetCheckData").click( function () {
//		console.log(123123)
//		var checkStatus = table.checkStatus('boxId');
//		console.log(checkStatus)
//	
//		});
//   


    //调整价格
    $("#price").on("click", function () {
        var index = layui.layer.open({
            title: "调整价格",
            type: 2,
            content: "/goods/priceChange?caseNo=" + $("#caseNo").val()
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        })
    })

    $(".layui-icon-refresh-3").on("click", function () {
        location.reload();
    })
    
    //是否开启
    form.on('switch(isShow)', function (data) {
        var sata = 0;
        if (data.elem.checked) {
            sata = 1;
        }
        $.get("/main/boxOpenOrClose?boxId=" + data.value + "&status=" + sata, function (data) {
            if (!data.success) {
                // 提示失败
                layer.open({
                    title: '温馨提示'
                    , content: data.message
                });
                tableIns.reload();
            } else {
                layer.msg("操作成功");
//                tableIns.reload();
            }
        }, "json");
    })

    form.on('switch(myisSize)', function (data) {
        // console.debug(12321)
        var sata = 0;
        if (data.elem.checked) {
            sata = 1;
        }
        var caseNo = $("#caseNo").val()
        $.post("/main/changeCaseSize", {
                caseNo: caseNo,
                size: sata
            },
            function (data) {
                if (!data.success) {
                    // 提示失败
                    layer.open({
                        title: '温馨提示',
                        content: data.message
                    });
                    window.location.reload();
                } else {
                    layer.msg("操作成功");
//                    window.location.reload();
                }
            });
    })
    
    //是否开启离线短信通知(1.是   0.否）
    form.on('switch(isBoxOfflineNotity)', function (data) {
        var sata = 0;
        if (data.elem.checked) {
            sata = 1;           
        }
        $("#isBoxOfflineNotity").val(this.checked?1:0);
        isBoxOfflineNotitySwitch(sata);
    })
    
    function isBoxOfflineNotitySwitch(value){
    	var el = $("#bindPhoneNumber");
    	if(value==1){
    		el.show();
    		el.attr("lay-verify","required|phone"); 
    	}else{
    		el.attr("lay-verify",""); 
    		el.hide();
    	}
    	form.render();
    }
    
    $(function(){
    	var sata = 0;
    	if($("#isBoxOfflineNotity")[0].checked){sata = 1;}
		isBoxOfflineNotitySwitch(sata);
    })

    //开门记录
    function stateRecord(record) {
        var index = layui.layer.open({
            title: "开门记录",
            type: 2,
            content: "/stateRecord/index",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (record) {
                    body.find(".boxId").attr("value", record.boxId);
                    body.find(".caseNo").val(record.caseNo);
                    body.find(".doorNum").val(record.doorNum);
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回柜子详情', '.layui-layer-setwin .layui-layer-close', {
                        tips: 2
                    });
                }, 500)
            }
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        })
    }

    //开门
    function openDoor(open) {
        $.get("/main/openBoxByAdmin?caseNo=" + open.caseNo + "&boxNum=" + open.doorNum, function (data) {
            if (!data.success) {
                // 提示失败
                layer.open({
                    title: '温馨提示'
                    , content: data.message
                });

                tableIns.reload();
            } else {
                layer.msg("开启成功");
            }
        })
    }

    //清除
    function cleanState(clean) {
        $.get("/main/boxClear?boxId=" + clean.boxId, function (data) {
            if (!data.success) {
                // 提示失败
                layer.open({
                    title: '温馨提示'
                    , content: data.message
                });

                tableIns.reload();
            } else {
                layer.msg("清除成功，请妥善保管储物柜的物品，以免产生纠纷！！！");
                tableIns.reload();
            }
        })
    }

    //列表操作
    table.on('tool(stateEdit)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        if (layEvent === 'record') { //编辑
            stateRecord(data);
        }
        if (layEvent === 'clean') {
            cleanState(data);
        }
        if (layEvent === 'open') {
            openDoor(data);
        }
    });

    //头工具栏事件
    table.on('toolbar(stateEdit)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var layEvent = obj.event;
        var data = checkStatus.data;
        var ids = "";
        if (layEvent === 'getCheckData') { //编辑
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    ids += data[i].boxId + ',';
                }
                $.get("/main/boxClearBatch?boxIds=" + ids, function (data) {
                    if (!data.success) {
                        // 提示失败
                        layer.open({
                            title: '温馨提示'
                            , content: data.message
                        });
                        tableIns.reload();
                    } else {
                        layer.msg("清除成功，请妥善保管储物柜的物品，以免产生纠纷！！！");
                        tableIns.reload();
                    }
                })
            } else {
                layer.alert("请选择要清除的柜子");
            }
        }else if(layEvent === 'openDoors'){
            $.get("/main/box/openAll?caseNo=" + $("#caseNo").val(), function (data) {
                if(data.success){
                    layer.msg(data.message);
                }else{
                    layer.msg("开门失败");
                }
            })
        }
    });

    form.on('submit(formDemo)', function (data) {
        $.post("/main/BoxChange", data.field, function (rest) {
            if (rest.success) {
                layer.msg("编辑成功");
                //parent.window.location.reload();
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index);
                parent.layui.table.reload('stateListTable') 
            } else {
                layer.msg(rest.message);
            }
        })
    })
})


